package pl.edu.mimuw.irs.core.model.design.resource;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.Collection;
import java.util.LinkedHashSet;

public class Requirements extends LinkedHashSet<Requirement> implements IHolder<Requirement>, PropertyChangeListener {

	private static final long serialVersionUID = -1687675896004951400L;

	// *** Properties
	public static final String REQUIREMENT = "REQUIREMENT";
	
	// *** Attributes

	private PropertyChangeSupport listeners;
	private String name;
	public PropertyChangeSupport getListeners() {
		if (listeners == null) listeners = new PropertyChangeSupport(this);
		return listeners;
	}
	public String getName() {
		if (name == null) return "Resources[" + size() + "]";
		else return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	// *** Constructors
	
	public Requirements() {
		
	}

	public Requirements(Requirements requirements) {
		for (Requirement requirement : requirements) {
			add((Requirement) requirement.copy());
		}
	}
	
	// *** Methods
	
	@Override
	public boolean add(Requirement e) {
		boolean retval = super.add(e);
		if (retval) {
			e.setRequirements(this);
			getListeners().firePropertyChange(REQUIREMENT, null, e);
		}
		e.addPropertyChangeListener(this);
		return retval;
	}
	
	@Override
	@Deprecated
	public boolean addAll(Collection<? extends Requirement> c) {
		throw new UnsupportedOperationException();
	}
	
	@Override
	public boolean remove(Object o) {
		boolean retval = super.remove(o);
		if (o instanceof Requirement) {
			Requirement requirement = (Requirement) o;
			getListeners().firePropertyChange(REQUIREMENT, requirement, null);
			if (requirement.getRequirements() == this) requirement.setRequirements(null);
			requirement.removePropertyChangeListener(this);
		}
		return retval;
	}
	
	@Override
	public boolean remove(Requirement element) {
		return this.remove((Object) element);
	}

	@Override
	@Deprecated
	public boolean removeAll(Collection<?> c) {
		throw new UnsupportedOperationException();
	}
	
	@Override
	@Deprecated
	public boolean retainAll(Collection<?> c) {
		throw new UnsupportedOperationException();
	}
	
	public void addPropertyChangeListener(PropertyChangeListener listener) {
		getListeners().addPropertyChangeListener(listener);
	}
	
	public void removePropertyChangeListener(PropertyChangeListener listener) {
		getListeners().removePropertyChangeListener(listener);
	}

	@Override
	public void propertyChange(PropertyChangeEvent arg0) {
		getListeners().firePropertyChange(arg0);
	}

}
